# 导入所需的调度器类和触发器类
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from datetime import datetime
from pytz import timezone
from django.conf import settings
import threading
lock = threading.RLock()
def _task_print():
    print('5秒',datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'))

def task_test():
    print('10秒',datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'))

def print_user():
    from home import models
    obj = models.UserModel.objects.all()
    for i in obj:
        print(i)
    print('-----------------------------------')

class Scheduler:
    flak = None
    def __new__(cls, *args, **kwargs):
        if cls.flak:

            return cls.flak
        else:
            with lock:
                print('执行了这个了')
                cls.flak = object.__new__(cls)
                return cls.flak

    def __init__(self):
        # 创建调度器实例,设置中国时间
        self.scheduler = BackgroundScheduler()
        self.scheduler.timezone = timezone(settings.TIME_ZONE)
        #1、使用内存存储定时任务信息
        jobstore_memory = MemoryJobStore()
        self.scheduler.add_jobstore(jobstore_memory)
        #2、使用redis存储定时任务信息
        # jobstore_redis = RedisJobStore(host='127.0.0.1', port=6379, db=0)
        # self.scheduler.add_jobstore(jobstore_redis)
    def __call__(self, *args, **kwargs):
        # 添加定时任务：单位参数seconds,minutes,hours,days
        # self.scheduler.add_job(_task_print, IntervalTrigger(seconds=5),id='_task_print',replace_existing=True)
        # self.scheduler.add_job(task_test, IntervalTrigger(seconds=10), id='task_test',replace_existing=True)
        # self.scheduler.add_job(print_user,IntervalTrigger(seconds=10),id='print_user',replace_existing=True)
        # 启动调度器
        self.scheduler.start()
